package com.pay.cloud.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.pay.cloud.Application;
import com.pay.cloud.ErrorListener;
import com.pay.cloud.activity.AbstractActivity;

public class AbstractFragment extends Fragment implements ErrorListener {
    private Activity activity;
    private Handler handler;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        handler = new Handler();
    }

    @Override
    public void onError(String msg) {
        if (activity instanceof ErrorListener) {
            handle(() -> ((ErrorListener)activity).onError(msg));
        } else {
            showToast(msg);
        }
    }

    protected final void showToast(String msg) {
        if (activity instanceof  AbstractActivity)
            handle(() -> ((AbstractActivity)activity).showToast(msg));
        else
            Toast.makeText(getContext(), msg, Toast.LENGTH_LONG);
    }

    protected final void showLoading() {
        if (activity instanceof  AbstractActivity)
            handler.post(() -> ((AbstractActivity)activity).showLoading());
    }

    protected final void hideLoading() {
        if (activity instanceof  AbstractActivity)
            handler.post(() -> ((AbstractActivity)activity).hideLoading());
    }

    protected void setMainFragment(Fragment fragment) {
        if (activity instanceof  AbstractActivity)
            handle(() -> ((AbstractActivity)activity).setMainFragment(fragment));
    }

    protected final void handle(Runnable run) {
        handler.post(run);
    }

    protected final void handleDelay(Runnable run, int lazy) {
        handler.postDelayed(run, lazy);
    }

    protected final void speak(String text) {
        Application.speak(text);
    }

    protected final void speak(int textId) {
        Application.speak(textId);
    }


}
